<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>WebSocket与Http | 欢迎来到小张的博客</title><meta name="keywords" content="通信协议"><meta name="author" content="Z_SiTong"><meta name="copyright" content="Z_SiTong"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="什么是Websocket Websocket 是一种网络通信协议，是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议  Websocket有什么特点 建立在TCP协议之上 性能开销小通信高效 协议标识符 ws wss（加密之后） 持久化网络通信协议 客户端可以与任意服务器通信  Websocket是什么样的协议，具体有什么优点 首先，Websocket是一个持久化的协议，相对于H">
<meta property="og:type" content="article">
<meta property="og:title" content="WebSocket与Http">
<meta property="og:url" content="https://zhang-sitong.gitee.io/blogs/lz_19/index.html">
<meta property="og:site_name" content="欢迎来到小张的博客">
<meta property="og:description" content="什么是Websocket Websocket 是一种网络通信协议，是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议  Websocket有什么特点 建立在TCP协议之上 性能开销小通信高效 协议标识符 ws wss（加密之后） 持久化网络通信协议 客户端可以与任意服务器通信  Websocket是什么样的协议，具体有什么优点 首先，Websocket是一个持久化的协议，相对于H">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/03/24/5IZl9AO2XLnjiWM.jpg">
<meta property="article:published_time" content="2019-03-24T06:10:52.000Z">
<meta property="article:modified_time" content="2021-03-24T12:32:55.587Z">
<meta property="article:author" content="Z_SiTong">
<meta property="article:tag" content="通信协议">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/03/24/5IZl9AO2XLnjiWM.jpg"><link rel="shortcut icon" href="/blogs/img/favicon.png"><link rel="canonical" href="https://zhang-sitong.gitee.io/blogs/lz_19/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blogs/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blogs/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
};

const saveToLocal = {
  // ttl 單位是 天
  set: function setWithExpiry(key, value, ttl) {
    if (ttl === 0) return
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}

// https://stackoverflow.com/questions/16839698/jquery-getscript-alternative-in-native-javascript
const getScript = url => new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.onerror = reject
  script.onload = script.onreadystatechange = function() {
    const loadState = this.readyState
    if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
    script.onload = script.onreadystatechange = null
    resolve()
  }
  document.head.appendChild(script)
})</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-24 20:32:55'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = 'false'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}})()</script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><div class="aplayer" data-id="6583040939" data-server="netease" data-type="playlist" data-fixed="true" data-listFolded="false" data-order="random" data-preload="auto"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/lete114/CDN/music/APlayer/APlayer.min.css"><script src="https://cdn.jsdelivr.net/gh/lete114/CDN/music/APlayer/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/meting@1.2.0/dist/Meting.min.js"></script><meta name="generator" content="Hexo 5.3.0"><link rel="alternate" href="/blogs/atom.xml" title="欢迎来到小张的博客" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/blogs/img/%E5%8D%9A%E5%AE%A2%E5%A4%B4%E5%83%8F.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blogs/archives/"><div class="headline">文章</div><div class="length-num">29</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blogs/tags/"><div class="headline">标签</div><div class="length-num">12</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blogs/categories/"><div class="headline">分类</div><div class="length-num">12</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blogs/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/link/"><i class="fa-fw fa fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://i.loli.net/2021/03/24/5IZl9AO2XLnjiWM.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blogs/">欢迎来到小张的博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blogs/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/link/"><i class="fa-fw fa fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/blogs/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">WebSocket与Http</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="fa-fw post-meta-icon far fa-calendar-alt"></i><span class="post-meta-label">发表于</span><time datetime="2019-03-24T06:10:52.000Z" title="undefined 2019-03-24 14:10:52">2019-03-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blogs/categories/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/">通信协议</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="什么是Websocket"><a href="#什么是Websocket" class="headerlink" title="什么是Websocket"></a>什么是Websocket</h2><ul>
<li>Websocket 是一种网络通信协议，是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议</li>
</ul>
<h2 id="Websocket有什么特点"><a href="#Websocket有什么特点" class="headerlink" title="Websocket有什么特点"></a>Websocket有什么特点</h2><ul>
<li>建立在TCP协议之上</li>
<li>性能开销小通信高效</li>
<li>协议标识符 ws wss（加密之后）</li>
<li>持久化网络通信协议</li>
<li>客户端可以与任意服务器通信</li>
</ul>
<h2 id="Websocket是什么样的协议，具体有什么优点"><a href="#Websocket是什么样的协议，具体有什么优点" class="headerlink" title="Websocket是什么样的协议，具体有什么优点"></a>Websocket是什么样的协议，具体有什么优点</h2><blockquote>
<p>首先，Websocket是一个持久化的协议，相对于HTTP这种非持久的协议来说<br>HTTP的生命周期通过 Request 来界定，也就是一个 Request 一个 Response ，那么在 HTTP1.0 中，这次HTTP请求就结束了。<br>在HTTP1.1中进行了改进，使得有一个keep-alive，也就是说，在一个HTTP连接中，可以发送多个Request，接收多个Response。但是请记住 Request = Response ， 在HTTP中永远是这样，也就是说一个request只能有一个response。而且这个response也是被动的，不能主动发起。</p>
</blockquote>
<h2 id="Websocket的作用"><a href="#Websocket的作用" class="headerlink" title="Websocket的作用"></a>Websocket的作用</h2><h3 id="1）ajax轮询"><a href="#1）ajax轮询" class="headerlink" title="1）ajax轮询"></a>1）ajax轮询</h3><pre><code>ajax轮询的原理非常简单，让浏览器隔个几秒就发送一次请求，询问服务器是否有新信息</code></pre>
<h3 id="2）long-poll长轮询"><a href="#2）long-poll长轮询" class="headerlink" title="2）long poll长轮询"></a>2）long poll长轮询</h3><pre><code>long poll 其实原理跟 ajax轮询 差不多，都是采用轮询的方式，不过采取的是阻塞模型（一直打电话，没收到就不挂电话），也就是说，客户端发起连接后，如果没消息，就一直不返回Response给客户端（对于PHP有最大执行时间，建议没消息，执行到一定时间也返回）。直到有消息才返回，返回完之后，客户端再次建立连接，周而复始。
从上面可以看出其实这两种方式，都是在不断地建立HTTP连接，关闭HTTP协议，由于HTTP是非状态性的，每次都要重新传输 identity info （鉴别信息），来告诉服务端你是谁。然后等待服务端处理，可以体现HTTP协议的另外一个特点，被动性。
何为被动性呢，其实就是，服务端不能主动联系客户端，只能有客户端发起。从上面很容易看出来，不管怎么样，上面这两种都是非常消耗资源的。
ajax轮询 需要服务器有很快的处理速度和资源。（速度）long poll 需要有很高的并发，也就是说同时接待客户的能力。（场地大小）</code></pre>
<h3 id="3）WebSocket"><a href="#3）WebSocket" class="headerlink" title="3）WebSocket"></a>3）WebSocket</h3><pre><code>Websocket解决了HTTP的这几个难题。首先，被动性，当服务器完成协议升级后（HTTP-&gt;Websocket），服务端就可以主动推送信息给客户端啦。解决了上面同步有延迟的问题。
解决服务器上消耗资源的问题：其实我们所用的程序是要经过两层代理的，即HTTP协议在Nginx等服务器的解析下，然后再传送给相应的Handler（php等）来处理。简单地说，我们有一个非常快速的 接线员（Nginx） ，他负责把问题转交给相应的 客服（Handler） 。Websocket就解决了这样一个难题，建立后，可以直接跟接线员建立持久连接，有信息的时候客服想办法通知接线员，然后接线员在统一转交给客户。
由于Websocket只需要一次HTTP握手，所以说整个通讯过程是建立在一次连接/状态中，也就避免了HTTP的非状态性，服务端会一直知道你的信息，直到你关闭请求，这样就解决了接线员要反复解析HTTP协议，还要查看identity info的信息。
目前唯一的问题是：不兼容低版本的IE</code></pre>
<h2 id="Websocket使用场景"><a href="#Websocket使用场景" class="headerlink" title="Websocket使用场景"></a>Websocket使用场景</h2><blockquote>
<p>社交聊天、弹幕、多玩家游戏、视频会议/聊天、在线教育、智能家居等需要高实时的场景</p>
</blockquote>
<h2 id="Websocket-四个事件，两个方法"><a href="#Websocket-四个事件，两个方法" class="headerlink" title="Websocket 四个事件，两个方法"></a>Websocket 四个事件，两个方法</h2><ul>
<li><h3 id="4个事件"><a href="#4个事件" class="headerlink" title="4个事件"></a>4个事件</h3><ul>
<li>open Socket.onopen 连接建立时触发</li>
<li>message Socket.onmessage 客户端接收服务端数据时触发</li>
<li>error Socket.onerror 通信发生错误时触发</li>
<li>close Socket.onclose 连接关闭时触发</li>
</ul>
</li>
<li><h3 id="2个方法"><a href="#2个方法" class="headerlink" title="2个方法"></a>2个方法</h3><ul>
<li>Socket.send() 使用连接发送数据</li>
<li>Socket.close() 关闭连接</li>
</ul>
</li>
</ul>
<hr>
<h2 id="什么是HTTP协议"><a href="#什么是HTTP协议" class="headerlink" title="什么是HTTP协议"></a>什么是HTTP协议</h2><ul>
<li>超文本传输协议，本质上是一种通信协议。用来将html从服务端传送到客户端</li>
</ul>
<h2 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h2><ul>
<li>简单快速<blockquote>
<p>客户向服务器请求服务时，只需传送请求方法和路径</p>
</blockquote>
</li>
<li>无连接<blockquote>
<p>限制每次连接只处理一个请求。服务器处理完客户的请求，并收到客户的应答后，即断开连接。采用这种方式可以节省传输时间</p>
</blockquote>
</li>
<li>无状态<blockquote>
<p>协议对于事务处理没有记忆能力。缺少状态意味着如果后续处理需要前面的信息，则它必须重传，这样可能导致每次连接传送的数据量增大。另一方面，在服务器不需要先前信息时它的应答就较快</p>
</blockquote>
</li>
</ul>
<hr>
<h2 id="Websocket与http的关系"><a href="#Websocket与http的关系" class="headerlink" title="Websocket与http的关系"></a>Websocket与http的关系</h2><ul>
<li><h3 id="相同点"><a href="#相同点" class="headerlink" title="相同点"></a>相同点</h3><ol>
<li>都是一样基于TCP的，都是可靠性传输协议。</li>
<li>都是应用层协议。</li>
</ol>
</li>
<li><h3 id="不同点"><a href="#不同点" class="headerlink" title="不同点"></a>不同点</h3><ol>
<li>WebSocket是双向通信协议，模拟Socket协议，可以双向发送或接受信息。HTTP是单向的。</li>
<li>WebSocket是需要浏览器和服务器握手进行建立连接的。而http是浏览器发起向服务器的连接，服务器预先并不知道这个连接。</li>
</ol>
</li>
</ul>
<hr>
<h2 id="Websocket实例"><a href="#Websocket实例" class="headerlink" title="Websocket实例"></a>Websocket实例</h2><ul>
<li><h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><ul>
<li>pip install -i <a target="_blank" rel="noopener" href="https://pypi.tuna.tsinghua.edu.cn/simple">https://pypi.tuna.tsinghua.edu.cn/simple</a> dwebsocket</li>
</ul>
</li>
<li><h3 id="定义视图文件的逻辑views-py"><a href="#定义视图文件的逻辑views-py" class="headerlink" title="定义视图文件的逻辑views.py"></a>定义视图文件的逻辑views.py</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#导入websocket装饰器</span></span><br><span class="line"><span class="keyword">from</span> dwebsocket.decorators <span class="keyword">import</span> accept_websocket</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#接收前端信息</span></span><br><span class="line"><span class="meta">@accept_websocket</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_socket</span>(<span class="params">request</span>):</span></span><br><span class="line">    <span class="keyword">if</span> request.is_websocket():</span><br><span class="line">        <span class="keyword">for</span> message <span class="keyword">in</span> request.websocket:</span><br><span class="line">            c=<span class="built_in">str</span>(message,encoding=<span class="string">&#x27;utf-8&#x27;</span>)</span><br><span class="line">            print(c)</span><br><span class="line">            request.websocket.send(message)</span><br><span class="line"></span><br><span class="line"><span class="comment">#主动推送消息</span></span><br><span class="line"><span class="meta">@accept_websocket</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_websocket</span>(<span class="params">request</span>):</span></span><br><span class="line">    <span class="keyword">if</span> request.is_websocket():</span><br><span class="line">        <span class="keyword">while</span> <span class="number">1</span>:</span><br><span class="line">            time.sleep(<span class="number">1</span>) <span class="comment">## 向前端发送时间</span></span><br><span class="line">            dit = &#123;</span><br><span class="line">                <span class="string">&#x27;time&#x27;</span>:time.strftime(<span class="string">&#x27;%Y.%m.%d %H:%M:%S&#x27;</span>,time.localtime(time.time()))</span><br><span class="line">            &#125;</span><br><span class="line">            request.websocket.send(json.dumps(dit))</span><br></pre></td></tr></table></figure></li>
<li><h3 id="路由配置"><a href="#路由配置" class="headerlink" title="路由配置"></a>路由配置</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#websocket</span></span><br><span class="line">path(<span class="string">&#x27;test_socket&#x27;</span>,test_socket),</span><br><span class="line">path(<span class="string">&#x27;test_websocket&#x27;</span>,test_websocket),</span><br></pre></td></tr></table></figure></li>
<li><h3 id="定义前端发送消息的页面-–-socket-vue"><a href="#定义前端发送消息的页面-–-socket-vue" class="headerlink" title="定义前端发送消息的页面 – socket.vue"></a>定义前端发送消息的页面 – socket.vue</h3><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div&gt;</span><br><span class="line">    &lt;<span class="built_in">input</span> <span class="built_in">id</span>=<span class="string">&quot;chat-message-input&quot;</span> <span class="built_in">type</span>=<span class="string">&quot;text&quot;</span> size=<span class="string">&quot;100&quot;</span>/&gt;&lt;br/&gt;</span><br><span class="line">    &lt;<span class="built_in">input</span> <span class="built_in">id</span>=<span class="string">&quot;chat-message-submit&quot;</span> <span class="built_in">type</span>=<span class="string">&quot;button&quot;</span> value=<span class="string">&quot;Send&quot;</span> @click=<span class="string">&#x27;sendmessage()&#x27;</span>/&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script&gt;</span><br><span class="line">export default &#123;</span><br><span class="line">  name: <span class="string">&quot;socket&quot;</span>,</span><br><span class="line">  data() &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    sendmessage() &#123;</span><br><span class="line"></span><br><span class="line">      window.s.send(document.getElementById(<span class="string">&quot;chat-message-input&quot;</span>).value);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line">    //生成socket对象</span><br><span class="line">    var socket = new WebSocket(<span class="string">&quot;ws://127.0.0.1:8000/z/test_socket/&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    socket.onopen = function () &#123;</span><br><span class="line">      console.log(<span class="string">&#x27;WebSocket open&#x27;</span>);//成功连接上Websocket</span><br><span class="line">    &#125;;</span><br><span class="line">    socket.onmessage = function (e) &#123;</span><br><span class="line">      console.log(<span class="string">&#x27;message: &#x27;</span> + e.data);//打印服务端返回的数据</span><br><span class="line">    &#125;;</span><br><span class="line">    socket.onclose = function (e) &#123;</span><br><span class="line">      console.log(e);</span><br><span class="line">      socket.close(); //关闭TCP连接</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">if</span> (socket.readyState == WebSocket.OPEN) &#123;</span><br><span class="line">      socket.onopen();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    window.s = socket;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/script&gt;</span><br><span class="line"></span><br><span class="line">&lt;style scoped&gt;</span><br><span class="line"></span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure></li>
<li><h3 id="然后再定义一个页面，测试后台的主动推送-–-socket-push-vue"><a href="#然后再定义一个页面，测试后台的主动推送-–-socket-push-vue" class="headerlink" title="然后再定义一个页面，测试后台的主动推送 – socket_push.vue"></a>然后再定义一个页面，测试后台的主动推送 – socket_push.vue</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line"></span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script&gt;</span><br><span class="line">export default &#123;</span><br><span class="line">  name: <span class="string">&quot;socket_push&quot;</span>,</span><br><span class="line">  data() &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line">    //生成socket对象</span><br><span class="line">    var socket = new WebSocket(<span class="string">&quot;ws://127.0.0.1:8000/z/test_websocket/&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    socket.onopen = function () &#123;</span><br><span class="line">      console.log(<span class="string">&#x27;WebSocket open&#x27;</span>);//成功连接上Websocket</span><br><span class="line">    &#125;;</span><br><span class="line">    socket.onmessage = function (e) &#123;</span><br><span class="line">      console.log(<span class="string">&#x27;message: &#x27;</span> + e.data);//打印服务端返回的数据</span><br><span class="line">    &#125;;</span><br><span class="line">    socket.onclose = function (e) &#123;</span><br><span class="line">      console.log(e);</span><br><span class="line">      socket.close(); //关闭TCP连接</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">if</span> (socket.readyState == WebSocket.OPEN) &#123;</span><br><span class="line">      socket.onopen();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/script&gt;</span><br><span class="line"></span><br><span class="line">&lt;style scoped&gt;</span><br><span class="line"></span><br><span class="line">&lt;/style&gt;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Z_SiTong</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhang-sitong.gitee.io/blogs/lz_19/">https://zhang-sitong.gitee.io/blogs/lz_19/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhang-sitong.gitee.io/blogs" target="_blank">欢迎来到小张的博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blogs/tags/%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/">通信协议</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/03/24/5IZl9AO2XLnjiWM.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blogs/lz_20%20(%E6%8A%80%E6%9C%AF%E7%82%B9)/"><img class="prev-cover" src="https://i.loli.net/2021/03/29/nHq2BC7guU9e4cP.jpg" onerror="onerror=null;src='/blogs/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">技术点</div></div></a></div><div class="next-post pull-right"><a href="/blogs/lz_18/"><img class="next-cover" src="https://i.loli.net/2021/03/21/BNz2vCwnVTsXHrf.jpg" onerror="onerror=null;src='/blogs/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">MySQL和NoSQL</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="/blogs/img/%E5%8D%9A%E5%AE%A2%E5%A4%B4%E5%83%8F.jpg" onerror="this.onerror=null;this.src='/blogs/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Z_SiTong</div><div class="author-info__description"></div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blogs/archives/"><div class="headline">文章</div><div class="length-num">29</div></a></div><div class="card-info-data-item is-center"><a href="/blogs/tags/"><div class="headline">标签</div><div class="length-num">12</div></a></div><div class="card-info-data-item is-center"><a href="/blogs/categories/"><div class="headline">分类</div><div class="length-num">12</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFWebsocket"><span class="toc-number">1.</span> <span class="toc-text">什么是Websocket</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Websocket%E6%9C%89%E4%BB%80%E4%B9%88%E7%89%B9%E7%82%B9"><span class="toc-number">2.</span> <span class="toc-text">Websocket有什么特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Websocket%E6%98%AF%E4%BB%80%E4%B9%88%E6%A0%B7%E7%9A%84%E5%8D%8F%E8%AE%AE%EF%BC%8C%E5%85%B7%E4%BD%93%E6%9C%89%E4%BB%80%E4%B9%88%E4%BC%98%E7%82%B9"><span class="toc-number">3.</span> <span class="toc-text">Websocket是什么样的协议，具体有什么优点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Websocket%E7%9A%84%E4%BD%9C%E7%94%A8"><span class="toc-number">4.</span> <span class="toc-text">Websocket的作用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%EF%BC%89ajax%E8%BD%AE%E8%AF%A2"><span class="toc-number">4.1.</span> <span class="toc-text">1）ajax轮询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%EF%BC%89long-poll%E9%95%BF%E8%BD%AE%E8%AF%A2"><span class="toc-number">4.2.</span> <span class="toc-text">2）long poll长轮询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%EF%BC%89WebSocket"><span class="toc-number">4.3.</span> <span class="toc-text">3）WebSocket</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Websocket%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-number">5.</span> <span class="toc-text">Websocket使用场景</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Websocket-%E5%9B%9B%E4%B8%AA%E4%BA%8B%E4%BB%B6%EF%BC%8C%E4%B8%A4%E4%B8%AA%E6%96%B9%E6%B3%95"><span class="toc-number">6.</span> <span class="toc-text">Websocket 四个事件，两个方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E4%B8%AA%E4%BA%8B%E4%BB%B6"><span class="toc-number">6.1.</span> <span class="toc-text">4个事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E4%B8%AA%E6%96%B9%E6%B3%95"><span class="toc-number">6.2.</span> <span class="toc-text">2个方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFHTTP%E5%8D%8F%E8%AE%AE"><span class="toc-number">7.</span> <span class="toc-text">什么是HTTP协议</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%89%B9%E7%82%B9"><span class="toc-number">8.</span> <span class="toc-text">特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Websocket%E4%B8%8Ehttp%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="toc-number">9.</span> <span class="toc-text">Websocket与http的关系</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%B8%E5%90%8C%E7%82%B9"><span class="toc-number">9.1.</span> <span class="toc-text">相同点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%8D%E5%90%8C%E7%82%B9"><span class="toc-number">9.2.</span> <span class="toc-text">不同点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Websocket%E5%AE%9E%E4%BE%8B"><span class="toc-number">10.</span> <span class="toc-text">Websocket实例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%89%E8%A3%85"><span class="toc-number">10.1.</span> <span class="toc-text">安装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E8%A7%86%E5%9B%BE%E6%96%87%E4%BB%B6%E7%9A%84%E9%80%BB%E8%BE%91views-py"><span class="toc-number">10.2.</span> <span class="toc-text">定义视图文件的逻辑views.py</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1%E9%85%8D%E7%BD%AE"><span class="toc-number">10.3.</span> <span class="toc-text">路由配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E5%89%8D%E7%AB%AF%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF%E7%9A%84%E9%A1%B5%E9%9D%A2-%E2%80%93-socket-vue"><span class="toc-number">10.4.</span> <span class="toc-text">定义前端发送消息的页面 – socket.vue</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%84%B6%E5%90%8E%E5%86%8D%E5%AE%9A%E4%B9%89%E4%B8%80%E4%B8%AA%E9%A1%B5%E9%9D%A2%EF%BC%8C%E6%B5%8B%E8%AF%95%E5%90%8E%E5%8F%B0%E7%9A%84%E4%B8%BB%E5%8A%A8%E6%8E%A8%E9%80%81-%E2%80%93-socket-push-vue"><span class="toc-number">10.5.</span> <span class="toc-text">然后再定义一个页面，测试后台的主动推送 – socket_push.vue</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blogs/lz_28/" title="多因子登录基础知识点"><img src="https://i.loli.net/2021/04/19/T9cDNdmovulPEbL.jpg" onerror="this.onerror=null;this.src='/blogs/img/404.jpg'" alt="多因子登录基础知识点"/></a><div class="content"><a class="title" href="/blogs/lz_28/" title="多因子登录基础知识点">多因子登录基础知识点</a><time datetime="2019-04-19T12:08:59.000Z" title="发表于 2019-04-19 20:08:59">2019-04-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blogs/lz_27/" title="基于Docker安装关系型数据库PostgrelSQL替代Mysql"><img src="https://i.loli.net/2021/04/19/QRXbxEvnLpBHuzI.jpg" onerror="this.onerror=null;this.src='/blogs/img/404.jpg'" alt="基于Docker安装关系型数据库PostgrelSQL替代Mysql"/></a><div class="content"><a class="title" href="/blogs/lz_27/" title="基于Docker安装关系型数据库PostgrelSQL替代Mysql">基于Docker安装关系型数据库PostgrelSQL替代Mysql</a><time datetime="2019-04-14T01:42:58.000Z" title="发表于 2019-04-14 09:42:58">2019-04-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blogs/lz_26/" title="json与pickle"><img src="https://i.loli.net/2021/04/13/DtnL4OVQM7bZjId.jpg" onerror="this.onerror=null;this.src='/blogs/img/404.jpg'" alt="json与pickle"/></a><div class="content"><a class="title" href="/blogs/lz_26/" title="json与pickle">json与pickle</a><time datetime="2019-04-12T07:48:41.000Z" title="发表于 2019-04-12 15:48:41">2019-04-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blogs/lz_25/" title="集合(set)的用法和使用场景，以及底层去重算法"><img src="https://i.loli.net/2021/04/08/Ji5dTUKsnoGjRBz.jpg" onerror="this.onerror=null;this.src='/blogs/img/404.jpg'" alt="集合(set)的用法和使用场景，以及底层去重算法"/></a><div class="content"><a class="title" href="/blogs/lz_25/" title="集合(set)的用法和使用场景，以及底层去重算法">集合(set)的用法和使用场景，以及底层去重算法</a><time datetime="2019-04-06T02:48:41.000Z" title="发表于 2019-04-06 10:48:41">2019-04-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blogs/lz_24/" title="openLDAP"><img src="https://i.loli.net/2021/04/07/nLeJybVMHwFNj7G.jpg" onerror="this.onerror=null;this.src='/blogs/img/404.jpg'" alt="openLDAP"/></a><div class="content"><a class="title" href="/blogs/lz_24/" title="openLDAP">openLDAP</a><time datetime="2019-03-31T08:52:13.000Z" title="发表于 2019-03-31 16:52:13">2019-03-31</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 <i style="color:#FF6A6A;animation: announ_animation 0.8s linear infinite;" class="fa fa-heartbeat"></i> Z_SiTong</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blogs/js/utils.js"></script><script src="/blogs/js/main.js"></script><script src="/blogs/js/search/local-search.js"></script><div class="js-pjax"></div><script src="https://cdn.jsdelivr.net/gh/lete114/CDN/Sum/sakura.js"></script><script src="https://cdn.jsdelivr.net/gh/lete114/CDN/Sum/title.js"></script>null<script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>